package com.carpedil.boot.service.impl;

import com.carpedil.boot.entity.City;
import com.carpedil.boot.entity.User;
import com.carpedil.boot.entity.dto.UserDTO;
import com.carpedil.boot.mapper.CityMapper;
import com.carpedil.boot.mapper.UserMapper;
import com.carpedil.boot.redis.JedisDb;
import com.carpedil.boot.service.UserService;
import com.carpedil.boot.util.SerializeUtil;
import com.carpedil.dto.ScoreDto;
import com.carpedil.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;

import java.util.List;

/** @author Administrator */
@Service
public class UserServiceImpl implements UserService {
  @Autowired UserMapper userMapper;
  @Autowired CityMapper cityMapper;
  @Autowired RestTemplate restTemplate;

  @Override
  public List<User> getUsers() {
    return userMapper.getUsers();
  }

  @Override
  public int registerUser(User user) {
    return userMapper.registerUser(user);
  }

  @Override
  public UserDto getUserByUserNameAndPassword(String username, String password) {
    User user = userMapper.getUserByUserNameAndPassword(username, password);
    return new UserDto()
        .setUsername(user.getUsername())
        .setPassword(user.getPassword())
        .setPerm(user.getPerm());
  }

  @Override
  public List<ScoreDto> login(String username, String password) {
    String url = "http://127.0.0.1:8001/auth/" + username + "/" + password;
    // 认证获取token
    String token = restTemplate.getForEntity(url, String.class).getBody();
    System.out.println("token = " + token);

    // RPC调用成绩系统的方法
    String tokenUrl = "http://127.0.0.1:8002/score/" + token;

    return restTemplate.getForEntity(tokenUrl, List.class).getBody();
  }

  @Override
  public UserDTO getUserTravelInfo(String username) {
    UserDTO userDTO = null;
    if (checkUserName(username)) {
      Jedis jdis = JedisDb.createJedis();
      byte[] bytes = jdis.get(username.getBytes());
      if (null != bytes) {
        userDTO = (UserDTO) SerializeUtil.decSerizlize(bytes);
        assert userDTO != null;
        userDTO.setDataFrom("Redis缓存数据");
        return userDTO;
      } else {
        System.out.println("无缓存数据-----> 正在查询数据库");
        List<City> cities = cityMapper.getTravelInfo(username);
        userDTO = new UserDTO();
        userDTO.setUsername(username);
        userDTO.setCities(cities);
        userDTO.setDataFrom("Mysql数据");
        // 序列化对象
        byte[] userBytes = SerializeUtil.serialize(userDTO);
        // 保存至redis  设置过期时间2分钟
        jdis.setex(username.getBytes(), 60 * 2, userBytes);
      }
    }
    return userDTO;
  }

  private boolean checkUserName(String username) {
    User user = userMapper.getUserByUserName(username);
    return null != user;
  }
}
